package com.maybach.web.framework.exception;

import com.maybach.common.enums.BaseConstants;
import com.maybach.web.constants.WebConstants;
import com.maybach.workflow.common.api.exception.FlowException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by houenxun on 15/12/9.
 * 多异常进行拦截，并统一跳转到结果页面上
 */
public class HandlerExceptionResolver implements org.springframework.web.servlet.HandlerExceptionResolver {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 未登陆访问了手续页面
        ModelAndView modelAndView = null;
        if(ex instanceof UnauthenticatedException){
             modelAndView = new ModelAndView(WebConstants.REDIRECT_PREFIX+"/login");
        }else if(ex instanceof FlowException){ //
            logger.error("没有权限操作", ex);
            modelAndView = new ModelAndView(WebConstants.COMMON_RESULT_PAGE);
            modelAndView.addObject(WebConstants.RESULT_CODE_KEY, BaseConstants.ResultCode.NO_AUTH);
            modelAndView.addObject(WebConstants.REDIRECT_URL_KEY, request.getParameter(WebConstants.REDIRECT_URL_KEY));
        } else{
            logger.error("处理异常", ex);
             modelAndView = new ModelAndView(WebConstants.COMMON_RESULT_PAGE);
            modelAndView.addObject(WebConstants.RESULT_CODE_KEY, BaseConstants.ResultCode.EXCEPTION);
            modelAndView.addObject(WebConstants.REDIRECT_URL_KEY, request.getParameter(WebConstants.REDIRECT_URL_KEY));

        }
        return modelAndView;
    }
}
